<template>
  <PageContainer>
    <section class="content-block carousel-section">
      <div class="block-header">
        <h2>精选内容</h2>
      </div>
      <AsyncState
        :loading="carouselLoading"
        :error="carouselError"
        :isEmpty="!carouselCards.length"
        emptyMessage="暂未获取到内容"
        :retry="fetchCarouselData"
      >
        <CarouselCard :cards="carouselCards" />
      </AsyncState>
    </section>

    <section class="content-block">
      <div class="block-header">
        <h2>讨论区最新动态</h2>
        <RouterLink class="text-link" to="/forum">进入讨论区</RouterLink>
      </div>
      <AsyncState
        :loading="postsLoading"
        :error="postsError"
        :isEmpty="!latestPosts.length"
        emptyMessage="讨论区还没有帖子，快去发布第一条吧"
        :retry="fetchPosts"
      >
        <div class="grid grid--posts">
          <InfoCard
            v-for="post in latestPosts"
            :key="post.id"
            :title="post.title"
            :description="post.excerpt"
            :meta="post.meta"
            :tags="post.tags"
            :to="`/forum/${post.id}`"
            clickable
          >
            <template #footer>
              <RouterLink :to="`/forum/${post.id}`" class="action-link">
                查看详情
              </RouterLink>
            </template>
          </InfoCard>
        </div>
      </AsyncState>
    </section>

    <section class="content-block">
      <div class="block-header">
        <h2>版本更新 &amp; 路线</h2>
      </div>
      <AsyncState
        :loading="versionLoading"
        :error="versionError"
        :isEmpty="!versionTimeline.length"
        emptyMessage="暂无版本记录"
        :retry="fetchVersion"
      >
        <div class="version-timeline">
          <div class="timeline-axis">
            <div class="axis-line"></div>
            <div
              v-for="(item, index) in versionTimeline"
              :key="item.version"
              class="timeline-node"
              :class="{ 'is-latest': index === versionTimeline.length - 1 }"
              :style="{ left: `${(index / (versionTimeline.length - 1 || 1)) * 100}%` }"
            >
              <div class="node-dot"></div>
              <div class="node-date">{{ formatDateOnly(item.date) }}</div>
            </div>
          </div>
          <div class="version-cards">
            <div
              v-for="(item, index) in versionTimeline"
              :key="item.version"
              class="version-card"
              :class="{ 'is-latest': index === versionTimeline.length - 1 }"
            >
              <div class="card-header">
                <h3 class="version-title">{{ item.version }}</h3>
                <span class="version-date">{{ formatDateOnly(item.date) }}</span>
              </div>
              <p class="version-summary">{{ item.summary }}</p>
              <ul v-if="item.highlights?.length" class="highlight-list">
                <li v-for="highlight in item.highlights" :key="highlight">
                  <span class="highlight-icon">✓</span>
                  {{ highlight }}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </AsyncState>
    </section>
  </PageContainer>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import PageContainer from '../components/PageContainer.vue'
import AsyncState from '../components/AsyncState.vue'
import InfoCard from '../components/InfoCard.vue'
import CarouselCard from '../components/CarouselCard.vue'
import {
  getSections,
  getPosts,
  getMetaVersion,
  getCarouselCards,
} from '../api/client'
import { useAsyncData } from '../composables/useAsyncData'
import { formatDateOnly, truncateText } from '../utils/formatters'

const sectionRoutes = {
  home: '/',
  introduction: '/introduction',
  shannon: '/shannon',
  elements: '/elements',
  applications: '/applications',
  future: '/future',
  forum: '/forum',
  about: '/about',
}

function resolveSectionLink(id) {
  return sectionRoutes[id] || '/'
}

const {
  data: sections,
  loading: sectionsLoading,
  error: sectionsError,
  execute: fetchSections,
} = useAsyncData(getSections, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

const {
  data: posts,
  loading: postsLoading,
  error: postsError,
  execute: fetchPosts,
} = useAsyncData(getPosts, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

const {
  data: versions,
  loading: versionLoading,
  error: versionError,
  execute: fetchVersion,
} = useAsyncData(getMetaVersion, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

const {
  data: carouselCardsData,
  loading: carouselLoading,
  error: carouselError,
  execute: fetchCarouselData,
} = useAsyncData(getCarouselCards, {
  initialValue: [],
  transform: (data) => data?.items ?? [],
})

onMounted(() => {
  fetchSections().catch(() => {})
  fetchPosts().catch(() => {})
  fetchVersion().catch(() => {})
  fetchCarouselData().catch(() => {})
})

const latestPosts = computed(() =>
  posts.value
    .slice()
    .sort((a, b) => new Date(b.created_at || 0) - new Date(a.created_at || 0))
    .slice(0, 3)
    .map((post) => ({
      ...post,
      excerpt: truncateText(post.content, 110),
      meta: [
        { label: '作者', value: post.author || '匿名用户' },
        { label: '发布时间', value: formatDateOnly(post.created_at) },
        { label: '点赞', value: post.likes ?? 0 },
        { label: '回复', value: post.replies?.length ?? 0 },
      ],
      tags: post.tags ?? [],
    })),
)

const versionTimeline = computed(() =>
  versions.value
    .slice()
    .sort((a, b) => new Date(a.date || 0) - new Date(b.date || 0)),
)

const latestVersion = computed(() => versionTimeline.value[versionTimeline.value.length - 1])

const latestVersionMeta = computed(() => {
  if (!latestVersion.value) return []
  return [{ label: '发布日期', value: formatDateOnly(latestVersion.value.date) }]
})

// 轮播卡片数据直接从后台获取
const carouselCards = computed(() => carouselCardsData.value)
</script>

<style scoped>
.content-block {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.carousel-section {
  margin-left: -32px;
  margin-right: -32px;
  padding-left: 32px;
  padding-right: 32px;
  width: calc(100% + 64px);
  max-width: 100vw;
  overflow: hidden;
  box-sizing: border-box;
}

.block-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
}

.block-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

.text-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
}

.text-link:hover {
  text-decoration: underline;
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
}

.grid--posts {
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
}

.action-link {
  font-size: 14px;
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
}

.action-link:hover {
  text-decoration: underline;
}

.version-timeline {
  display: flex;
  flex-direction: column;
  gap: 32px;
  padding: 20px 0;
}

.timeline-axis {
  position: relative;
  height: 80px;
  margin: 0 40px;
}

.axis-line {
  position: absolute;
  top: 40px;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(to right, #409eff, #67c23a);
  border-radius: 2px;
}

.timeline-node {
  position: absolute;
  top: 0;
  transform: translateX(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.node-dot {
  width: 16px;
  height: 16px;
  background: #fff;
  border: 4px solid #409eff;
  border-radius: 50%;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
  transition: all 0.3s ease;
}

.timeline-node.is-latest .node-dot {
  width: 20px;
  height: 20px;
  border-width: 5px;
  border-color: #67c23a;
  box-shadow: 0 0 0 4px rgba(103, 194, 58, 0.2);
}

.node-date {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  font-weight: 500;
}

.timeline-node.is-latest .node-date {
  color: #67c23a;
  font-weight: 600;
}

.version-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.version-card {
  border: 1px solid #ebeef5;
  border-radius: 12px;
  padding: 20px;
  background: #fff;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.version-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.15);
  border-color: rgba(64, 158, 255, 0.3);
}

.version-card.is-latest {
  border-color: rgba(103, 194, 58, 0.4);
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.05), rgba(255, 255, 255, 1));
  box-shadow: 0 4px 16px rgba(103, 194, 58, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.version-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

.version-card.is-latest .version-title {
  color: #67c23a;
}

.version-date {
  font-size: 13px;
  color: #909399;
  white-space: nowrap;
}

.version-summary {
  margin: 0;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
}

.highlight-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.highlight-list li {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  font-size: 13px;
  color: #606266;
  line-height: 1.5;
}

.highlight-icon {
  color: #67c23a;
  font-weight: bold;
  flex-shrink: 0;
  margin-top: 2px;
}

@media (max-width: 960px) {
  .version-cards {
    grid-template-columns: 1fr;
  }

  .timeline-axis {
    margin: 0 20px;
  }
}

@media (max-width: 640px) {
  .carousel-section {
    margin-left: -20px;
    margin-right: -20px;
    padding-left: 20px;
    padding-right: 20px;
    width: calc(100% + 40px);
  }

  .grid {
    grid-template-columns: 1fr;
  }

  .block-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .timeline-axis {
    height: 100px;
    margin: 0 10px;
  }

  .node-date {
    font-size: 11px;
  }

  .version-cards {
    gap: 16px;
  }

  .version-card {
    padding: 16px;
  }
}
</style>

